/*
 * 
 * 
 * 
 */

package com.haoxuer.discover.plug.data.plugs.diskfile;

import com.haoxuer.discover.plug.utils.OS;
import com.haoxuer.discover.plug.api.StoragePlugin;
import com.haoxuer.discover.plug.data.entity.PluginConfig;
import com.haoxuer.discover.plug.data.vo.FileInfo;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Component;

/**
 * Plugin - 本地文件存储
 */
@Component("diskFilePlugin")
public class DiskFilePlugin extends StoragePlugin {
  
  
  @Override
  public String getName() {
    return "磁盘存储插件";
  }
  
  @Override
  public String getVersion() {
    return "1.0";
  }
  

  @Override
  public String viewName() {
    return "diskfile";
  }

  @Override
  public void upload(String path, File file, String contentType) {
    PluginConfig pluginConfig = getPluginConfig();
    if (pluginConfig != null) {
      String disk = pluginConfig.getAttribute("disk");
      File destFile = new File(disk + path);
      try {
        FileUtils.moveFile(file, destFile);
        if (!OS.isWindows()) {
          Runtime.getRuntime().exec("chmod 444 " + destFile.getPath());
          Runtime.getRuntime().exec("chmod 777 " + destFile.getParentFile().getPath());
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  
  @Override
  public String getUrl(String path) {
    PluginConfig pluginConfig = getPluginConfig();
    if (pluginConfig != null) {
      String url = pluginConfig.getAttribute("url");
      return url + path;
    }
    return path;
  }
  
  @Override
  public List<FileInfo> browser(String path) {
    List<FileInfo> fileInfos = new ArrayList<FileInfo>();
    PluginConfig pluginConfig = getPluginConfig();
    if (pluginConfig != null) {
      String disk = pluginConfig.getAttribute("disk");
      File directory = new File(disk + path);
      if (directory.exists() && directory.isDirectory()) {
        for (File file : directory.listFiles()) {
          FileInfo fileInfo = new FileInfo();
          fileInfo.setName(file.getName());
          fileInfo.setUrl(path + file.getName());
          fileInfo.setIsDirectory(file.isDirectory());
          fileInfo.setSize(file.length());
          fileInfo.setLastModified(new Date(file.lastModified()));
          fileInfos.add(fileInfo);
        }
      }
    }
    
    return fileInfos;
  }
  
}